<?php

namespace app\common\model;

use think\facade\Db;
class CommonArticle extends Base
{
    // 追加属性
    protected $append = ['preview_url','category_id','category_path'];

    /**
     * 关联 管理员表
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo('app\admin\model\AdminUser', 'uid');
    }
    /**
     * 关联分类表
     * @return \think\model\relation\BelongsToMany
     */
    public function categories()
    {
        return $this->belongsToMany('CommonArticleCategory', 'common_article_category_rel', 'category_id', 'article_id');
    }

    //追加属性
    public function getCategoryIdAttr($value,$data)
    {
        $result = Db::name('common_article_category_rel')->where(['article_id'=>$data['id']])->column('category_id');
        return $result;
    }

    //追加属性
    public function getCategoryPathAttr($value,$data)
    {
        $result = Db::name('common_article_category_rel')->where(['article_id'=>$data['id']])->column('category_id');
        $pathList = Db::name('common_article_category')->where('id','in',$result)->column('parent_path');
        $idArr = [];
        foreach ($pathList as $key => $val){
            $idArr = array_merge($idArr,explode(',', $val));
        }
        return array_map('intval',$idArr);
    }

    public function getPreviewUrlAttr($value,$data)
    {
        if(empty($data['thumbnail'])){
            return '';
        }
        $filesystemConfig = config('filesystem.disks.public');
        return request()->domain().$filesystemConfig['url'].$data['thumbnail'];
    }

}
